 //
//  TKYSearchProgressResultController.m
//  ProgressReportProject
//
//  Created by apple on 2018/4/23.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYSearchProgressResultController.h"
#import "TKYSearchBarView.h"
#import "TKYProgressModel.h"
#import "TKYProgressViewCell.h"
#import "TKYFindTreeController.h"
#import "TKYUpdateProgressController.h"
#import "TKYProgressDetailsController.h"
#import "TKYFindTreeModel.h"
#import "TKYFindTreeView.h"
@interface TKYSearchProgressResultController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)TKYSearchBarView *searchBar;
@property (nonatomic, strong)BaseTabelView *tableV;

@property (nonatomic, strong)TKYFindTreeController *treeVc;

/**
 显示没有数据的view
 */
@property (nonatomic, strong)UIView *noDataView;

/**
 当前显示的页数
 */
@property (nonatomic, assign)NSInteger currentPage;

/**
 进度日报列表数据
 */
@property (nonatomic, strong)NSMutableArray <TKYProgressModel *>*progressModelS;

@property (nonatomic, strong)TKYFindTreeModel *nodelModel;

@property (nonatomic, strong)TKYFindTreeView *findTreeView;

@end

@implementation TKYSearchProgressResultController
/**
 视图将要出现
 */
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableV.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

/**
 设置界面
 */
- (void)setupUI{
     self.view.backgroundColor = kMainColour;
     self.navigationItem.title = @"搜索";
//    self.navigationItem.titleView = self.searchBar;
     [self.view addSubview:self.searchBar];

     self.progressModelS = [NSMutableArray array];
}

- (void)loadMoreData{
    self.currentPage ++;
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&limit=20&page=%ld&flowId=%@",kProgressApiBaseUrl,kProgressReportListUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],self.currentPage,self.nodelModel.ids];
    [SVProgressHUD showSVProgressImage:nil Duration:1.0 FontSize:16 status:@"正在加载"];
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        NSArray *arr = [TKYProgressModel  mj_objectArrayWithKeyValuesArray:response[@"pageUtil"][@"list"]];
        [self.progressModelS addObjectsFromArray:arr];
        [self.tableV reloadData];
        int total = [response[@"pageUtil"][@"totalCount"] intValue];
        if (self.progressModelS.count == total) { // 全部加载完毕
            // 提示用户:没有更多数据
            [self.tableV.mj_footer endRefreshingWithNoMoreData];
            //            self.tableV.mj_footer.hidden = YES;
        } else { // 还没有加载完全
            // 结束刷新
            [self.tableV.mj_footer endRefreshing];
        }
        //NSLog(@"%@",response[@"rows"]);
    } failure:^(NSError *error) {
        [SVProgressHUD showSVProgressImage:nil Duration:1.0 FontSize:16 status:@"网络错误,请稍候再试"];
        [self.tableV.mj_footer endRefreshing];
    }];
}

- (void)loadNewData{
    [self requestSearchText:self.nodelModel.ids];
}

- (void)deleteProgressModel:(TKYProgressModel *)progressModel{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",kProgressApiBaseUrl,kDeleteProgressReportUrl];
    NSDictionary *parameterDict = @{
                                    @"token":[[NSUserDefaults standardUserDefaults]objectForKey:kToken],
                                    @"id":progressModel.ID
                                    };
    [KHttpRequestTool POST:url parameters:parameterDict success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"删除成功"];
            //[SVProgressHUD dismiss];
        }else{
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:response[@"msg"]];
        }
        [self.tableV reloadData];
        [self.tableV.mj_header endRefreshing ];
    } failure:^(NSError *error) {
        [SVProgressHUD showSVProgressImage:nil Duration:1.0 FontSize:16 status:@"网络错误,请稍候再试"];
    }];
}

//请求搜索后的数据
- (void)requestSearchText:(NSString *)searchStr{
    self.currentPage = 1;
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&limit=20&page=%ld&flowId=%@",kProgressApiBaseUrl,kProgressReportListUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],self.currentPage,searchStr];
    
    NSString  *urlUTF  = [url  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [SVProgressHUD showWithStatus:@"正在请求数据..."];
    [KHttpRequestTool GET:urlUTF parameters:nil success:^(id response) {
        
        if ([response[@"code"] integerValue] == 0) {
            self.progressModelS = [TKYProgressModel  mj_objectArrayWithKeyValuesArray:response[@"pageUtil"][@"list"]];
        }else{
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:response[@"msg"]];
        }
        [self.tableV reloadData];
        [SVProgressHUD dismiss];
        [self.tableV.mj_header endRefreshing ];
    } failure:^(NSError *error) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"网络错误,请稍候再试"];
        [self.tableV.mj_header endRefreshing ];
    }];
}

#pragma mark-- UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    // 控制"没有数据"的提醒
    self.noDataView.hidden = (self.progressModelS.count != 0);
    return self.progressModelS.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 95;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TKYProgressViewCell *cell = [tableView dequeueReusableCellWithIdentifier:KProgressViewCellID];
    cell.progressModel = self.progressModelS[indexPath.row];
    return cell;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TKYProgressModel *model = self.progressModelS[indexPath.row];
    //删除
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        [self deleteProgressModel:model];
        NSLog(@"删除");
        [self.progressModelS removeObject:model];
        [self.tableV reloadData];
    }];
    
    //修改
    UITableViewRowAction *updataAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"修改"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"修改");
        TKYUpdateProgressController *updateVC = [[TKYUpdateProgressController alloc]init];
        updateVC.progressModel = model;
        [self.navigationController pushViewController:updateVC animated:YES];
    }];
    deleteAction.backgroundColor = [UIColor grayColor];
    return @[deleteAction, updataAction];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    TKYProgressModel *model = self.progressModelS[indexPath.row];
    TKYProgressDetailsController *progressDetailVC = [[TKYProgressDetailsController alloc]init];
    progressDetailVC.progressModel = model;
    [self.navigationController pushViewController:progressDetailVC animated:YES];
}

- (BaseTabelView *)tableV{
    if (_tableV == nil) {
        _tableV = [[BaseTabelView alloc]initWithFrame:CGRectMake(0,self.searchBar.kx_bottom, kScreenWidth, kScreenHeight - self.searchBar.kx_height) style:UITableViewStylePlain];
        _tableV.delegate = self;
        _tableV.dataSource = self;
        [_tableV registerNib:[UINib nibWithNibName:@"TKYProgressViewCell" bundle:nil] forCellReuseIdentifier:KProgressViewCellID];
        self.tableV.mj_footer = [TKYRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        self.tableV.mj_header = [TKYRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableV.tableFooterView = [[UIView alloc] init];
    }
    return _tableV;
}


- (TKYSearchBarView *)searchBar {
    if (!_searchBar) {
        if (IS_iPhoneX ) {
             _searchBar = [[TKYSearchBarView alloc] initWithFrame:CGRectMake(0.f, 88.f, self.view.kx_width, 44.f)];
        }else{
            _searchBar = [[TKYSearchBarView alloc] initWithFrame:CGRectMake(0.f, 64.f, self.view.kx_width, 44.f)];
        }
        __weak typeof(self) weakSelf = self;
        _searchBar.seachbarBlock = ^(UIButton *button) {
            [weakSelf.view addSubview:weakSelf.findTreeView];
//            [SVProgressHUD show];
//            weakSelf.treeVc = [[TKYFindTreeViewController alloc]init];
//            weakSelf.treeVc.selectedBlock = ^(TKYFindTreeModel *nodeModel) {
//            weakSelf.nodelModel = nodeModel;
//           weakSelf.searchBar.textField.text = nodeModel.name;
//
//            };
//            [weakSelf.navigationController pushViewController:weakSelf.treeVc animated:YES];
//            [SVProgressHUD dismiss];
        };
        _searchBar.seachbarBtnBlock = ^(UIButton *button) {
             [weakSelf requestSearchText:weakSelf.nodelModel.ids];
             [weakSelf.view addSubview:weakSelf.tableV];
        };
    }
    return _searchBar;
}


/**
 提示没有数据view
 */
- (UIView *)noDataView
{
    if (!_noDataView) {
        // 添加一个"没有数据"的提醒
        _noDataView = [[UIView alloc]init];
        [self.view addSubview:_noDataView];
        UILabel *label = [[UILabel alloc]init];
        label.textColor  = [UIColor grayColor];
        label.text = @"没有搜索内容";
        [_noDataView addSubview:label];
        [label autoCenterInSuperview];
        [_noDataView autoCenterInSuperview];
    }
    return _noDataView;
}

- (TKYFindTreeView *)findTreeView{
    if (_findTreeView == nil ) {
        _findTreeView = [[TKYFindTreeView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        __weak typeof(self) weakSelf = self;
        _findTreeView.selectedfindTreeModelBlock = ^(TKYFindTreeModel *findTreeModel) {
            weakSelf.nodelModel = findTreeModel;
            weakSelf.searchBar.textField.text = findTreeModel.name;
        };
    }
    return _findTreeView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
